package org.jeecg.modules.uniubi.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.modules.employee.entity.Employee;
import org.jeecg.modules.employee.service.IEmployeeService;
import org.jeecg.modules.uniubi.util.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

@Api(tags = "宇泛")
@RestController
@RequestMapping("/uniubi")
@Slf4j
public class ApiUtil {

    @Autowired
    private HttpClientUtil httpClientUtil;
    @Autowired
    private IEmployeeService employeeService;
    @Value("${uniubi.url}")
    private String path;

    @AutoLog(value = "（分页）查询已创建的识别主体信息")
    @ApiOperation(value = "（分页）查询已创建的识别主体信息", notes = "（分页）查询已创建的识别主体信息")
    @PostMapping("/admit/page")
    public Result<?> admitPage(@RequestParam(name = "length") String length){
        String url = path+"/v2/admit/page";
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("index", 1);
        jsonObject.put("length", length);
        jsonObject.put("faceNum", -1);
        JSONObject response = httpClientUtil.doPost(url, jsonObject);
        log.info("response:{}",response);
        if ("WO_SUS1000".equals(response.getString("code"))){
            JSONObject data = response.getJSONObject("data");
            JSONArray content = data.getJSONArray("content");
            for (int i = 0; i < content.size(); i++) {
                JSONObject item = content.getJSONObject(i);
                if (!item.getJSONArray("faces").isEmpty()){
                    item.put("faceUrl", item.getJSONArray("faces").getJSONObject(0).getString("faceUrl"));
                }
            }
            List<Employee> javaList = content.toJavaList(Employee.class);
            employeeService.saveBatch(javaList);
            return Result.OK(javaList);
        }
        return Result.OK(response);
    }


    @AutoLog("识别主体授权")
    @ApiOperation(value = "识别主体授权",notes = "识别主体授权")
    @PostMapping("/authorization")
    public Result<?> authorization(@RequestParam(name = "createTime") String creatTime){//E03C1CB453445401
        LambdaQueryWrapper<Employee> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(Employee::getCreateTime, creatTime);
        List<Employee> list = employeeService.list(wrapper);
        if (list.isEmpty()){
            return Result.OK();
        } else {
            String url = path + "/v2/auth/device";
            JSONObject finalResponse = new JSONObject(); // 用于保存最终合并的响应

            // 每批次最多处理100个元素
            int batchSize = 90;
            for (int i = 0; i < list.size(); i += batchSize) {
                // 获取当前批次的子列表
                List<Employee> subList = list.subList(i, Math.min(i + batchSize, list.size()));
                // 将当前批次的admitGuid连接成字符串
                String collect = subList.stream()
                        .map(Employee::getAdmitGuid)
                        .collect(Collectors.joining(","));

                JSONObject jsonObject = new JSONObject();
                jsonObject.put("deviceNo", "E03C1CB453445401");
                jsonObject.put("admitGuids", collect);

                // 发送请求并获取响应
                JSONObject response = httpClientUtil.doPost(url, jsonObject);
                // 根据实际情况决定如何处理每个请求的响应
                // 这里简单地将所有响应合并到finalResponse中，可能需要根据实际需求调整
                finalResponse.put("response_" + (i / batchSize + 1), response); // 示例：为每个响应添加一个唯一键
            }
            LambdaUpdateWrapper<Employee> updateWrapper = Wrappers.lambdaUpdate();
            updateWrapper.eq(Employee::getCreateTime, creatTime);
            updateWrapper.set(Employee::getStatus, "2");
            employeeService.update(updateWrapper);
            log.info("finalResponse: {}", finalResponse);
            return Result.OK("授权完成");
        }
    }

}
